from flask import Flask, render_template, request, url_for, redirect, session
from flask_sqlalchemy import SQLAlchemy
from apps.spider import searchEngineSpider, biquSpider
import config
import json
from apps.funcBlueprints import funcSearch
from apps.admin import admin

app = Flask(__name__)
app.register_blueprint(funcSearch, url_prefix="/fiction")
app.register_blueprint(admin, url_prefix="/admin")
app.debug = True
app.config.from_object(config.config_dict.get("test"))
db = SQLAlchemy(app)


@app.route("/")
def toSearch():
    return render_template("search.html")


@app.route("/parseCatalogue", methods=["POST"])
def parseCatalogue():
    data = json.loads(request.form.get('data'))
    baidu_url = data["baidu_url"]
    baidu_title = data["baidu_title"]
    session["baidu_url"] = baidu_url
    session["baidu_title"] = baidu_title
    # print("parseCatalogue:",session)
    # print("baidu_url:", baidu_url,baidu_title)
    novelCatalogue = biquSpider.getNovelHtml(baidu_url, {"User-Agent": searchEngineSpider.randomUA()})

    return 'redirect(url_for("toCatalogue",baidu_title=baidu_title))'


# 测试
@app.route('/get')
def get():
    # session['username']
    # session.get('username')
    print(session.get("username"))
    print(session.get("baidu_url"))
    print(session)
    return "session.get('username')"


@app.route("/testajax", methods=["GET", "POST"])
def testajax():
    a = request.form.get("data")
    print(a)
    return render_template("testajax.html")


@app.route('/sendAjax2', methods=['POST'])
def sendAjax2():
    # password = request.form.get('password')
    # username = request.args.get('username')

    data = json.loads(request.form.get('data2'))
    username = data['username']
    password = data['username']
    print(username)
    print(password)
    return "46575"


@app.route('/toaj2')
def toaj2():
    return render_template("t1.html")


if __name__ == "__main__":
    app.run()
